'use client'

import { Typography } from '@mui/material'
import Box from '@mui/material/Box'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { type MRT_ColumnDef } from 'material-react-table'
import { useRouter } from 'next/navigation'
import { useMemo } from 'react'

import { Table } from '@/components/Table'

import {
	type IClient,
	type IClients,
	clientsColumns
} from '@/types/client.types'

import { DASHBOARD_PAGES } from '@/config/pages-url.config'

import { clientService } from '@/services/clients.service'

export const Clients = () => {
	const {
		data, //your data and api response will probably be different
		isError,
		isRefetching,
		isLoading,
		refetch
	} = useQuery<IClients>({
		queryKey: [
			'clients'
			// columnFilters, //refetch when columnFilters changes
			// globalFilter, //refetch when globalFilter changes
			// pagination.pageIndex, //refetch when pagination.pageIndex changes
			// pagination.pageSize, //refetch when pagination.pageSize changes
			// sorting //refetch when sorting changes
		],
		queryFn: async () => {
			return await clientService.fetchMany()
			// return await clientService.fetchClients({
			// 	offset: pagination.pageIndex * pagination.pageSize,
			// 	limit: pagination.pageSize,
			// 	columnFilters: JSON.stringify(columnFilters ?? []),
			// 	globalFilter: globalFilter ?? '',
			// 	sorting: JSON.stringify(sorting ?? [])
			// })
		},
		placeholderData: keepPreviousData, //don't go to 0 rows when refetching or paginating to next page
		refetchOnWindowFocus: false //don't refetch when the user switches tabs
	})

	const { push } = useRouter()

	const columns = useMemo<MRT_ColumnDef<IClient>[]>(() => clientsColumns, [])

	return (
		<Table
			columns={columns}
			count={data?.count ?? 0}
			data={data?.results ?? []}
			initSorting={[{ id: 'id', desc: false }]}
			isError={isError}
			isLoading={isLoading}
			isRefetching={isRefetching}
			refetch={refetch}
			defaultPinnedColumns={['id', 'full_name']}
			handleView={id => push(`${DASHBOARD_PAGES.CLIENT}/${id}`)}
			createBtn={{
				label: 'Создать нового',
				action: () => push(DASHBOARD_PAGES.CLIENT_NEW)
			}}
			enableExpandAll={false}
			renderDetailPanel={({ row }) => (
				<Box>
					<Typography variant={'h6'}>Заметка:</Typography>
					<Typography>
						{row.original.note.length ? row.original.note : '-'}
					</Typography>
				</Box>
			)}
		/>
	)
}
